<?php
/*
 * @Author: wanzhengxin
 * @Date: 2021-07-09 14:41:01
 */


namespace app\index\service;

use think\Queue;
use think\facade\Cache;
use think\Request;
class WeChatService
{
    /**
     * @var \EasyWeChat\MiniProgram\Application
     */
    protected $app;
    protected $token = null;
    protected $allopenid = [];
    /**
     * 配置项
     * @var array
     */
    public function __construct($data)
    {
        $this ->APPID = $data['app_id'];
        $this->subsiby = array(
            "wx7316676cbe8e5c4b" =>"5bc3c539d88cf2a568856e8be1f0a75b",//方克
            'wx707275aa364d343f' => "41a923b3538c004866a3367492ee3007",//龙城
            'wxe0bb949bb097b477' => "af2a9eb4aa018e919ebb3dd656a2b776",//关二
        );
       
    }
    //获取openid和
    public function push($a)
       {
           $params = [
               'touser' => $a['openid'],
               "template_id"=>'Dr1SFV_MUGkCbcsz-01PnMgO3QMy5tzQyaqndPXX_FQ',
               "lang"=>"zh_CN",
               "url"=>'https://www.funcnum.com/',
               "data"=>[
                   "first"=>[
                       "value"=>'近期该打'.$a['name'].'了！',
                       "color"=>"#173177"
                   ],
                   "keyword1"=>[
                       "value"=>$a['time'],
                       "color"=>"#173177"
                   ],
                   "keyword2"=>[
                       "value"=>$a['address'],
                       "color"=>"#173177"
                   ],
                   "remark"=>[
                       "value"=>"请及时来打第".$a['remark']."针，下一针会再次提醒"
                   ]
               ]
           ];
           $Token = $this->getToken($a['app_id']);
           $t= $Token;
           $access_token =  $t;
           $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $access_token;
           $result = send_post($url,$params);
           return $result;
       }

    //龙城的信息报送通知
    public function pushlc($a)
    {
        $params = [
            'touser' => $a['openid'],
            "template_id"=>'_ugHsTGxAQG9KzpobVDraIwxOqT8-fupVD9L46yHtl8',
            "lang"=>"zh_CN",
            "url"=>$a['url'],
            "data"=>[
                "first"=>[
                    "value"=>$a['name'],//标题
                    "color"=>"#173177"
                ],
                "keyword1"=>[//报送类型
                    "value"=>$a['address'],//报送单位
                    "color"=>"#173177"
                ],
                "keyword2"=>[
                    "value"=>$a['type'],//消息类型
                    "color"=>"#173177"
                ],
                "keyword3"=>[
                    "value"=>$a['time'],//time，时间
                    "color"=>"#173177"
                ],
                "keyword4"=>[
                    "value"=>$a['context']//内容
                ],
                "remark"=>[
                    "value"=>$a['remark'],
                    "color"=>"#173177"
                ]
            ]
        ];
        $access_token = $this->getToken($a['app_id']);
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $access_token;
        $result = send_post($url,$params);
        return $result;
    }
    //关二的信息报送通知
    public function pushlcG2($a)
    {
        $params = [
            'touser' => $a['openid'],
            "template_id"=>'5xyOQJ61nUOtclNza3ju-ugr6jZGhoja-xaLN93QUIA',
            "lang"=>"zh_CN",
            "url"=>$a['url'],
            "data"=>[
                "first"=>[
                    "value"=>$a['name'],//标题
                    "color"=>"#173177"
                ],
                "keyword1"=>[//报送类型
                    "value"=>$a['address'],//报送单位
                    "color"=>"#173177"
                ],
                "keyword2"=>[
                    "value"=>$a['type'],//消息类型
                    "color"=>"#173177"
                ],
                "keyword3"=>[
                    "value"=>$a['time'],//time，时间
                    "color"=>"#173177"
                ],
                "keyword4"=>[
                    "value"=>$a['context']//内容
                ],
                "remark"=>[
                    "value"=>$a['remark'],
                    "color"=>"#173177"
                ]
            ]
        ];
        $access_token = $this->getToken($a['app_id']);
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $access_token;
        $result = send_post($url,$params);
        return $result;
    }
    //获取小程序的access_token
    public function getToken($APPID){
        //开发者使用登陆凭证 code 获取 session_key 和 openid
        $AppSecret = $this->subsiby[$APPID];//自己配置
        $url = "https://api.weixin.qq.com/cgi-bin/stable_token";
        $parmas =[
            "grant_type" =>"client_credential",
            "appid" =>$APPID,
            "secret" =>$AppSecret
        ]; 
        
        $t = $this->APPID."token";
        $token = Cache::get($t);
        $is_true = true;
        $ACCESS_TOKEN =$token;
        $callback ="https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=".$ACCESS_TOKEN;
        $callarr = send_post($callback,[]);  // 一个使用curl实现的get方法请求
        $callarr = json_decode($callarr,true);
        if(isset($callarr["errcode"])){
            if($callarr['errcode'] != 0 ){
                $is_true = false;
                // dump('无效');
            }
        }
        if($token == false || $is_true == false){
            $a = send_post($url,$parmas);
            $a = json_decode($a,true);
            // dump($a);
            if(isset($a["access_token"])){
                $t = $this->APPID."token";
                Cache::set($t,$a['access_token'],7000);
                $token = Cache::get($t);
                // dump('改变了');
            }
        }else{
            // dump('有效');
        }
        return $token;
    }

    //获取微信消息模版
    public function gettemplate(){
        $APPID = $this->APPID;
        $ACCESS_TOKEN =  $this->getToken($APPID);;
        $url ="https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token=".$ACCESS_TOKEN;
        $arr = get_curl_json($url);  // 一个使用curl实现的get方法请求
        return $arr;
        
    }
    //获取openid列表 {}
    public function getUserOpenId($next_openid='',&$d=[]){
        $APPID = $this->APPID;
        $ACCESS_TOKEN = $this->getToken($APPID);
        $url ="https://api.weixin.qq.com/cgi-bin/user/get?access_token=".$ACCESS_TOKEN."&next_openid=".$next_openid;
        $arr = get_curl_json($url);  // 一个使用curl实现的get方法请求
        if(isset($arr['data'])){
            $nest_openid = $arr['next_openid'];
            $d = array_merge($d,$arr['data']['openid']);
            $this->getUserOpenId($nest_openid,$d);
            return $d;
        }else{
            return $d;
        }
        
    }

   
    //获取openid22222列表 {}2并加入队列
    public function getUserOpenId2($next_openid='',&$count,$data){
        $APPID = $this->APPID;
        $ACCESS_TOKEN = $this->getToken($APPID);
        $url ="https://api.weixin.qq.com/cgi-bin/user/get?access_token=".$ACCESS_TOKEN."&next_openid=".$next_openid;
        $arr = get_curl_json($url);  // 一个使用curl实现的get方法请求
        if(isset($arr['data'])){
            $count ++;
            $nest_openid = $arr['next_openid'];
            foreach($arr['data']['openid'] as $value){
                $a=array('app_id'=>$APPID,'openid'=> $value,'name'=>$data['name'],'time'=>$data['time'],'url'=>$data['url'],'type'=>$data['type'],'address'=>$data['unit'],'context'=>$data['context'],'remark'=>$data['remark']);
                $queueName = 'pushQueue'.$count;
                $isPushed =false;
                $isPushed = Queue::push(TestQueue::class, $a,$queueName);
                unset($a);
                if ($isPushed !=false) {
                    dump('用户['.$value.']'." 加入.'$queueName'.成功");
                    unset($isPushed);
                } else {
                    dump("队列加入失败");
                    unset($isPushed);
                }
            }
            $this->getUserOpenId2($nest_openid,$count,$data);
        }
    }
   
}
